package com.jxccp.ui.view;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.jxccp.im.callback.JXEventListner;
import com.jxccp.im.chat.common.entity.JXTraderConfig;
import com.jxccp.im.chat.common.message.JXConversation;
import com.jxccp.im.chat.common.message.JXMessage;
import com.jxccp.im.chat.common.message.JXMessageAttribute;
import com.jxccp.im.chat.manager.JXConfigManager;
import com.jxccp.im.chat.manager.JXEventNotifier;
import com.jxccp.im.chat.manager.JXImManager;
import com.jxccp.im.util.JIDUtil;
import com.jxccp.im.util.log.JXLog;
import com.jxccp.jivesoftware.smack.util.MD5;
import com.jxccp.jivesoftware.smack.util.stringencoder.Base64;
import com.jxccp.ui.JXAccountHelper;
import com.jxccp.ui.JXConstants;
import com.jxccp.ui.JXUiHelper;
import com.jxccp.ui.R;
import com.jxccp.ui.utils.JXNotificationUtils;
import com.jxccp.ui.view.adapter.JXConversationAdatpter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;

public class JXConversationActivity extends JXBaseActivity implements View.OnClickListener,
        JXEventListner, JXUiHelper.OnConversationListener {

    private String Tag = "JXConversationActivity";

    private ImageView mbackImg;

    private ListView mConversationLV;

    private ProgressBar mloadingPB;

    private JXConversationAdatpter mConversationAdatpter;

    private List<JXConversation> conversations;

    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initConversation();
        loadingConversations();
        JXUiHelper.getInstance().setConversationListListener(this);
        if (JXUiHelper.getInstance().getmTitleBgColorId() != JXUiHelper.INVALID_INT) {
            findViewById(R.id.rl_root).setBackgroundColor(getResources().getColor(JXUiHelper.getInstance().getmTitleBgColorId()));
        }

        if (JXUiHelper.getInstance().getmTitleTextColorResId() != JXUiHelper.INVALID_INT) {
            ((TextView)findViewById(R.id.tv_actionTitle)).setTextColor(
                    getResources().getColor(JXUiHelper.getInstance().getmTitleTextColorResId()));
        }

        if (JXUiHelper.getInstance().getmTitleLeftImgResId() != JXUiHelper.INVALID_INT) {
            ((ImageView)findViewById(R.id.iv_left)).setImageResource(JXUiHelper.getInstance().getmTitleLeftImgResId());
        }
    }

    public void initView() {
        setContentView(R.layout.jx_activity_conversation);
        mbackImg = (ImageView) findViewById(R.id.iv_left);
        mConversationLV = (ListView) findViewById(R.id.lv_conversations);
        mloadingPB = (ProgressBar) findViewById(R.id.pb_loading);
        mbackImg.setOnClickListener(this);
        JXImManager.Message.getInstance().registerEventListener(this);
    }

    public void initConversation() {
        String username = null;
        String password = null;
        boolean hasAccount = false;
        sharedPreferences = this.getSharedPreferences(JXAccountHelper.CONFIG, this.MODE_PRIVATE);
        final SharedPreferences.Editor editor = sharedPreferences.edit();
        if (JXAccountHelper.getCustomerConfigCid() != null) {
            JXLog.d(JXLog.Module.mcs, Tag, "initConversation", "cid not null , init by cid");
            hasAccount = sharedPreferences.getBoolean(
                    JXImManager.getInstance().getAppKey() + JXAccountHelper.SP_SHORT_TOKEN_FLAG,
                    false);
            boolean isSameUser = sharedPreferences.getString(JXImManager.getInstance().getAppKey
                    () + JXAccountHelper
                    .SP_CID, "jxtest123")
                    .equals(JXAccountHelper.getCustomerConfigCid());
            if (hasAccount && isSameUser) {
                String encodeShortToken = sharedPreferences.getString(
                        JXImManager.getInstance().getAppKey() + "_" + JXAccountHelper
                                .SP_SHORT_TOKEN, "");
                username = JIDUtil.getUsernameFromPrefixName(
                        Base64.decodeToString(encodeShortToken));
            }else {
                username = MD5.hex(JXAccountHelper.getCustomerConfigCid());
            }
        } else {
            JXLog.d(JXLog.Module.mcs, Tag, "initConversation", "cid is null , init normal");
            hasAccount = sharedPreferences.getBoolean(JXConfigManager.getInstance().getAppKey()
                    + JXAccountHelper.SP_LOGIN_FLAG, false);
            if (hasAccount) {
                String encodeUsername = sharedPreferences.getString(
                        JXConfigManager.getInstance().getAppKey() + "_" + JXAccountHelper
                                .SP_USERNAMAE, "");
                username = JIDUtil.getUsernameFromPrefixName(Base64.decodeToString(encodeUsername));
                String encodePassword = sharedPreferences.getString(
                        JXImManager.getInstance().getAppKey() + "_" + JXAccountHelper.SP_PASSWORD,
                        "");
                password = JIDUtil.getUsernameFromPrefixName(
                        Base64.decodeToString(encodePassword));
            }
        }
        if (!TextUtils.isEmpty(username)) {
            JXImManager.McsUser.getInstance().initDbWithUsername(username);
            JXImManager.Conversation.getInstance().loadAllConversations();
        }
    }


    public void loadingConversations() {
        List<JXConversation> allConversations = JXImManager.Conversation.getInstance()
                .getAllConversations();
        JXLog.d(JXLog.Module.mcs, Tag, "loadingConversations", "conversation = " +
                allConversations);
        conversations = new ArrayList<>();
        Object[] objectList = allConversations.toArray();
        List<JXConversation> templist = new ArrayList<>();
        for (Object object : objectList) {
            JXConversation conversation = (JXConversation) object;
            if (conversation.getChatType() == JXMessage.ChatType.CUSTOMER_SERVICE) {
                templist.add(conversation);
            }
        }
        LinkedHashSet<JXConversation> set = new LinkedHashSet<JXConversation>(templist.size());
        set.addAll(templist);
        templist.clear();
        templist.addAll(set);
        conversations.addAll(templist);

        mConversationAdatpter = new JXConversationAdatpter(this, conversations);
        mConversationLV.setAdapter(mConversationAdatpter);
        mConversationLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                JXConversation jxConversation = conversations.get(position);
                JXTraderConfig jxTraderConfig = new JXTraderConfig();
                jxTraderConfig.setName(jxConversation.getSubject());
                jxTraderConfig.setPid(jxConversation.getPid());
                jxTraderConfig.setLogoUrl(jxConversation.getLogoUrl());
                jxTraderConfig.setSuborgId(jxConversation.getSuborgId());
                JXImManager.Config.getInstance().setTraderConfig(jxTraderConfig);
                Intent intent = new Intent(JXConversationActivity.this, JXInitActivity.class)
                        .putExtra(JXConstants.EXTRA_SUBORG_ID_KEY, jxConversation.getSuborgId());
                startActivityForResult(intent, JXUiHelper.JX_CONVERSATION_REQUEST_CODE);

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        refreshConversationList();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        JXImManager.Message.getInstance().removeEventListener(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        JXUiHelper.getInstance().setConversationPage(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        JXUiHelper.getInstance().setConversationPage(true);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_left) {
            finish();
        } else {

        }
    }

    @Override
    public void onEvent(JXEventNotifier jxEventNotifier) {
        switch (jxEventNotifier.getEvent()) {
            case MESSAGE_NEW:
                final JXMessage message = (JXMessage) jxEventNotifier.getData();
                String type = (String) message.getAttributes().get(JXMessageAttribute.TYPE.value());
                if (!JXUiHelper.getInstance().isNotifyEndMsg() && !TextUtils.isEmpty(type) &&
                        (type.equals(JXMessageAttribute.TYPE_VALUE_EVALUATED)
                                || type.equals(JXMessageAttribute.TYPE_VALUE_ENDED)
                                || type.equals(JXMessageAttribute.TYPE_VALUE_AUTO_CLOSE_FOR_AGENT)
                                || type.equals(JXMessageAttribute.TYPE_VALUE_AUTO_CLOSE_FOR_VISITOR)
                                || message.getType() == JXMessage.Type.EVALUATION)) {
                    mConversationLV.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            refreshConversationList();
                        }
                    }, 100);
                } else {
                    refreshConversationList();
                }
                break;
            default:
                break;
        }

    }

    @Override
    public void onConversationChanged() {
        refreshConversationList();
    }

    public void refreshConversationList() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                List<JXConversation> allConversations = JXImManager.Conversation.getInstance()
                        .getAllConversations();
                Object[] objectList = allConversations.toArray();
                List<JXConversation> templist = new ArrayList<>();
                for (Object object : objectList) {
                    JXConversation conversation = (JXConversation) object;
                    if (conversation.getChatType() == JXMessage.ChatType.CUSTOMER_SERVICE) {
                        templist.add(conversation);
                    }
                }
                LinkedHashSet<JXConversation> set = new LinkedHashSet<JXConversation>(templist.size());
                set.addAll(templist);
                templist.clear();
                templist.addAll(set);
                conversations.clear();
                conversations.addAll(templist);
                mConversationAdatpter.notifyDataSetChanged();
            }
        });
    }

}
